package com.biostime.qdingding.modules.qd.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.biostime.qdingding.common.utils.Encodes;
import com.biostime.qdingding.common.web.BaseController;

/**
 * CDN资源控制Controller
 * @author king
 * @version 2015-11-05
 */
@Controller
@RequestMapping(value = "/download")
public class DownloadController extends BaseController {
	
	@RequestMapping("downloadfile")
	public void downloadFile(HttpServletRequest request,HttpServletResponse response){
		String path = request.getParameter("filepath");
		String filePath = null;
		if(path.substring(path.length()-5, path.length()-1).contains("-")){//图片文件
			path = path.replace("-", "/");
			int index = path.indexOf("/", path.length()-5);
			path = path.substring(0, index) +"."+path.substring(index+1);
			filePath="/home/soleil/tomcat-qdingding/webapps/"+path;
		}else{//普通类型文件
			filePath="/home/soleil/tomcat-qdingding/webapps/"+path.replaceFirst("/", "");
		}
		logger.debug(filePath);
		response.reset();
		response.setContentType("application/octet-stream; charset=utf-8");
		response.setHeader("Content-Disposition", "attachment; filename="
				+ Encodes.urlEncode(request.getParameter("filename")));
		File file = new File(filePath);
		logger.debug("===============文件地址:"+file.getPath());
		logger.debug("===============文件长度:"+file.length());
		logger.debug("============文件是否存在:"+file.exists());
			try {
				FileInputStream fis = new FileInputStream(file);
				OutputStream os = response.getOutputStream();
				byte buffer[] = new byte[1024*8];
				int count = 0;
				while((count=fis.read(buffer)) != -1){
					os.write(buffer,0,count);
					os.flush();
				}
				os.close();
				fis.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
		}
	}
}